package com.campus.merchant.service;

import com.campus.merchant.bean.data.BusinessDataQueryParam;
import com.campus.merchant.mapper.data.BusinessDataMapper;
import com.campus.merchant.vo.data.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 经营数据Service
 *
 * @author ZhaoYuJie
 * @since 2025-01-25
 */
@Service
@RequiredArgsConstructor
public class BusinessDataService {

    private final BusinessDataMapper businessDataMapper;

    /**
     * 获取经营数据概览
     *
     * @param param 查询参数
     * @return 经营数据概览
     */
    public BusinessDataOverviewVO getBusinessDataOverview(BusinessDataQueryParam param) {
        BusinessDataOverviewVO overview = new BusinessDataOverviewVO();
        
        // 转换日期格式，添加时间部分
        String startDateTime = param.getStartDate() + " 00:00:00";
        String endDateTime = param.getEndDate() + " 23:59:59";
        
        // 查询订单数量
        Integer orderCount = businessDataMapper.getOrderCount(
            param.getMerchantId(), 
            startDateTime, 
            endDateTime
        );
        overview.setOrderCount(orderCount != null ? orderCount : 0);
        
        // 查询总收入
        BigDecimal totalIncome = businessDataMapper.getTotalIncome(
            param.getMerchantId(), 
            startDateTime, 
            endDateTime
        );
        overview.setTotalIncome(totalIncome != null ? totalIncome : BigDecimal.ZERO);
        
        return overview;
    }

    /**
     * 获取经营数据图表
     *
     * @param param 查询参数
     * @return 经营数据图表
     */
    public BusinessDataChartsVO getBusinessDataCharts(BusinessDataQueryParam param) {
        BusinessDataChartsVO charts = new BusinessDataChartsVO();
        
        // 获取订单趋势数据
        OrderTrendChartVO orderTrend = getOrderTrendChart(param);
        charts.setOrderTrend(orderTrend);
        
        // 获取热销商品数据
        HotGoodsChartVO hotGoods = getHotGoodsChart(param);
        charts.setHotGoods(hotGoods);
        
        return charts;
    }

    /**
     * 获取订单趋势图表数据
     */
    private OrderTrendChartVO getOrderTrendChart(BusinessDataQueryParam param) {
        OrderTrendChartVO orderTrend = new OrderTrendChartVO();
        
        // 生成日期范围
        List<String> dateRange = generateDateRange(param.getStartDate(), param.getEndDate());
        orderTrend.setXAxis(dateRange);
        
        // 转换日期格式，添加时间部分
        String startDateTime = param.getStartDate() + " 00:00:00";
        String endDateTime = param.getEndDate() + " 23:59:59";
        
        // 查询订单趋势数据
        List<Map<String, Object>> trendData = businessDataMapper.getOrderTrendData(
            param.getMerchantId(), 
            startDateTime, 
            endDateTime
        );
        
        // 将查询结果转换为Map，便于查找
        Map<String, Integer> dataMap = trendData.stream()
            .collect(Collectors.toMap(
                item -> item.get("date").toString(),
                item -> ((Number) item.get("count")).intValue()
            ));
        
        // 填充每日订单数量，没有数据的日期填0
        List<Integer> series = dateRange.stream()
            .map(date -> dataMap.getOrDefault(date, 0))
            .collect(Collectors.toList());
        orderTrend.setSeries(series);
        
        return orderTrend;
    }

    /**
     * 获取热销商品图表数据
     */
    private HotGoodsChartVO getHotGoodsChart(BusinessDataQueryParam param) {
        HotGoodsChartVO hotGoods = new HotGoodsChartVO();
        
        // 转换日期格式，添加时间部分
        String startDateTime = param.getStartDate() + " 00:00:00";
        String endDateTime = param.getEndDate() + " 23:59:59";
        
        // 查询热销商品数据，限制前10名
        List<Map<String, Object>> goodsData = businessDataMapper.getHotGoodsData(
            param.getMerchantId(), 
            startDateTime, 
            endDateTime,
            10
        );
        
        // 提取商品名称和销量
        List<String> yAxis = goodsData.stream()
            .map(item -> item.get("goodsName").toString())
            .collect(Collectors.toList());
        
        List<Integer> series = goodsData.stream()
            .map(item -> ((Number) item.get("totalQuantity")).intValue())
            .collect(Collectors.toList());
        
        hotGoods.setYAxis(yAxis);
        hotGoods.setSeries(series);
        
        return hotGoods;
    }

    /**
     * 生成日期范围
     */
    private List<String> generateDateRange(String startDate, String endDate) {
        List<String> dateRange = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);
        
        LocalDate current = start;
        while (!current.isAfter(end)) {
            dateRange.add(current.format(formatter));
            current = current.plusDays(1);
        }
        
        return dateRange;
    }
}